package public

import (
	"context"
	"fmt"
	"goProject/api/auth"
	"goProject/cfg"
	"goProject/db"
	"goProject/table"
	"net/http"
	"time"

	"gitee.com/ruige_fun/util/rlog"

	"gitee.com/ruige_fun/util/std"
	"github.com/kataras/iris/v12"
)

type pLogin struct {
	User string `json:"user" validate:"required,min=6,max=20"`
	Pwd  string `json:"pwd" validate:"required,min=6,max=255"`
}

func login(c iris.Context) {
	var p pLogin
	err := c.ReadJSON(&p)
	if err != nil {
		c.JSON(std.NewResp(http.StatusBadRequest, "参数校验失败", nil, nil))
		return
	}
	if v := db.RedisToken.Get(context.Background(), fmt.Sprint(cfg.Config.Main.ProjectName+"_login_blacklist_", p.User, "_", c.RemoteAddr())).Val(); v != "" {
		c.JSON(std.NewResp(http.StatusBadRequest, "距离上次输错密码时间过短，请稍后重试。", nil, nil))
		return
	}
	var u table.User
	err = db.MySQL.Where("`username` = ?", p.User).First(&u).Error
	if err != nil {
		db.RedisToken.Set(context.Background(), fmt.Sprint(cfg.Config.Main.ProjectName+"_login_blacklist_", p.User, "_", c.RemoteAddr()), time.Now().Unix()+10, time.Second*10) //黑名单
		c.JSON(std.NewResp(http.StatusBadRequest, "用户名或密码错误，请 10 秒后重试。", nil, nil))
		return
	}
	if false == auth.VerifyPassword(u, p.Pwd) {
		db.RedisToken.Set(context.Background(), fmt.Sprint(cfg.Config.Main.ProjectName+"_login_blacklist_", p.User, "_", c.RemoteAddr()), time.Now().Unix()+10, time.Second*10) //黑名单
		c.JSON(std.NewResp(http.StatusBadRequest, "用户名或密码错误，请 10 秒后重试。", nil, nil))
		return
	}
	if u.Lock == 2 {
		c.JSON(std.NewResp(http.StatusBadRequest, "您的账号已被锁定，请联系管理员解决。", nil, nil))
		return
	}
	var info table.Profile
	db.MySQL.Where("`id` = ?", u.ID).First(&info)
	if info.ID > 0 {
		_ = auth.Role.Set(fmt.Sprint(u.ID), int64(info.RoleID)) //更新一下该用户的权限信息
	}
	token := auth.NewToken(u, c.RemoteAddr())
	c.JSON(std.NewResp(http.StatusOK, "", token, nil))
	rlog.Success(c.RemoteAddr(), "登录了账号：", u)
	_ = auth.Token.Set(fmt.Sprint(u.ID), token)
}
